#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/client.hpp>
#include <iostream>

typedef websocketpp::client<websocketpp::config::asio_client> client;

// 全局变量用于存储要发送的消息
std::string message_to_send = "Hello WebSocket!";

// 消息处理函数
void on_message(client* c, websocketpp::connection_hdl hdl, client::message_ptr msg) {
    std::cout << "收到消息: " << msg->get_payload() << std::endl;
}

// 连接打开处理函数
void on_open(client* c, websocketpp::connection_hdl hdl) {
    std::cout << "连接已建立" << std::endl;
    // 在连接打开后发送消息
    websocketpp::lib::error_code ec;
    c->send(hdl, message_to_send, websocketpp::frame::opcode::text, ec);
    if (ec) {
        std::cout << "发送消息失败: " << ec.message() << std::endl;
    } else {
        std::cout << "消息已发送: " << message_to_send << std::endl;
    }
}

// 连接失败处理函数
void on_fail(client* c, websocketpp::connection_hdl hdl) {
    std::cout << "连接失败" << std::endl;
    client::connection_ptr con = c->get_con_from_hdl(hdl);
    std::cout << "错误信息: " << con->get_ec().message() << std::endl;
}

int main() {
    client ws_client;
    
    // 设置日志级别
    ws_client.set_access_channels(websocketpp::log::alevel::all);
    ws_client.clear_access_channels(websocketpp::log::alevel::frame_payload);
    
    // 注册处理器
    ws_client.set_message_handler(websocketpp::lib::bind(&on_message, &ws_client, 
        websocketpp::lib::placeholders::_1, websocketpp::lib::placeholders::_2));
    
    // 注册连接打开和失败处理器
    ws_client.set_open_handler(websocketpp::lib::bind(&on_open, &ws_client, 
        websocketpp::lib::placeholders::_1));
    ws_client.set_fail_handler(websocketpp::lib::bind(&on_fail, &ws_client, 
        websocketpp::lib::placeholders::_1));
    
    // 初始化 Asio
    ws_client.init_asio();
    
    // 创建连接
    websocketpp::lib::error_code ec;
    client::connection_ptr con = ws_client.get_connection("ws://localhost:9002", ec);
    
    if (ec) {
        std::cout << "无法创建连接，原因: " << ec.message() << std::endl;
        return -1;
    }
    
    // 连接（注意：此时连接并未立即建立）
    ws_client.connect(con);
    
    // 在线程中运行客户端
    websocketpp::lib::thread client_thread(&client::run, &ws_client);
    
    // 等待用户输入后再关闭
    std::cout << "按回车键退出..." << std::endl;
    std::cin.get();
    
    ws_client.stop();
    if (client_thread.joinable()) {
        client_thread.join();
    }
    
    return 0;
}